package com.linkoog.devtools.view_remark.action;

import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.impl.AbstractProjectViewPane;
import com.intellij.ide.projectView.impl.ProjectViewImpl;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.components.impl.stores.IProjectStore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.project.ProjectKt;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.linkoog.devtools.utils.StringUtils;
import com.linkoog.devtools.view_remark.persistent.ViewRemarkDataPersistent;
import org.jetbrains.annotations.NotNull;

public class AddSubfixRemarkAction extends AbstarctRemarkAction {


    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        Project project = event.getProject();
        if (project == null) return;

        VirtualFile virtualFile = event.getData(LangDataKeys.VIRTUAL_FILE);
        if (virtualFile == null) return;

        PsiElement psiElement = event.getData(LangDataKeys.PSI_ELEMENT);
        if (psiElement == null) return;

        IProjectStore store = ProjectKt.getStateStore(project);
        final VirtualFile projectDir = VfsUtil.findFile(store.getProjectBasePath(), false);
        if (projectDir == null) return;

        String relativePath = VfsUtilCore.getRelativePath(virtualFile, projectDir);
        final ViewRemarkDataPersistent viewRemarkDataPersistent = ViewRemarkDataPersistent.getInstance(project);
        String oldRemark = viewRemarkDataPersistent.getSubfix(relativePath);
        String remark = Messages.showInputDialog(project, oldRemark, "请输入后缀备注：", Messages.getQuestionIcon());
        if (remark != null){
            if (StringUtils.isBlank(remark)){
                viewRemarkDataPersistent.putSubfix(relativePath, null);
            } else {
                viewRemarkDataPersistent.putSubfix(relativePath, remark);
            }

            final ProjectView projectView = ProjectViewImpl.getInstance(project);
            final AbstractProjectViewPane currentProjectViewPane = projectView.getCurrentProjectViewPane();
            currentProjectViewPane.updateFrom(psiElement, false, false);
        }
    }
}
